<?php

namespace app\meizhuangapi\controller;
use app\meizhuangapi\model\UserAddress;

use app\api\controller\Address as AddressCon;
/**
 * 收货地址管理1
 */
class Address extends AddressCon{
    /**
     * 收货地址列表
     */
    public function lists(){
        $user = $this->getUser();
        $model = new UserAddress;
        $list = $model->getList($user['user_id']);
        $list=$list->toArray();
        $new=[];
        foreach ($list as $k=>$v){
            if($v['address_id']==$user['address_id']){
                if(!empty($v)){
                    $new=$v;
                }
                unset($list[$k]);
            }
        }
        if(!empty($new)){
            array_unshift($list,$new);
        }
        return $this->renderSuccess([
            'list' => $list,
            'default_id' => $user['address_id'],
        ]);
    }
    /*
     * 收货地址详情
     */
    public function detail(){
        $address_id=input('post.address_id');
        $user = $this->getUser();
        if($address_id==$user['address_id']){
            $default=true;
        }else{
            $default=false;
        }
        $detail = UserAddress::detail($user['user_id'], $address_id);
        $region = array_values($detail['region']);
        return $this->renderSuccess(compact('detail', 'region','default'));
    }

    /**
     * 编辑收货地址
     */
    public function edit($address_id){
        $user = $this->getUser();
        $model = UserAddress::detail($user['user_id'], $address_id);
        if ($model->edit($this->request->post(),$user)) {
            return $this->renderSuccess([], '更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 设为默认地址
     */
    public function setDefault($address_id){
        $user = $this->getUser();
        $model = UserAddress::detail($user['user_id'], $address_id);
        if ($model->setDefault($user)) {
            return $this->renderSuccess([], '设置成功');
        }
        return $this->renderError($model->getError() ?: '设置失败');
    }

    /**
     * 删除收货地址
     */
    public function delete($address_id){
        $user = $this->getUser();
        $model = UserAddress::detail($user['user_id'], $address_id);
        if ($model->remove($user)) {
            return $this->renderSuccess([], '删除成功');
        }
        return $this->renderError($model->getError() ?: '删除失败');
    }

}
